var VerificationCode = (function () {

    var canvas = document.getElementById("canvas");
    var context = canvas.getContext("2d");
    var button = document.getElementById("bt");
    var input = document.getElementById("text");
    var num;
    var validationMessage = document.getElementById("validation-message"); // 获取提示信息元素

    // 随机颜色函数
    function getColor() {
        var r = Math.floor(Math.random() * 256);
        var g = Math.floor(Math.random() * 256);
        var b = Math.floor(Math.random() * 256);
        return "rgb(" + r + "," + g + "," + b + ")";
    }

    // 绘制验证码
    function draw() {
        context.clearRect(0, 0, 120, 40);
        context.strokeRect(0, 0, 120, 40);
        var aCode = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "a", "b", "c", "d", "e", "f"];

        // 绘制字母
        var arr = [];
        for (var i = 0; i < 4; i++) {
            var x = 20 + i * 20;
            var y = 20 + 10 * Math.random();
            var index = Math.floor(Math.random() * aCode.length);
            var txt = aCode[index];
            context.font = "bold 20px 微软雅黑";
            context.fillStyle = getColor();
            context.translate(x, y);
            var deg = 90 * Math.random() * Math.PI / 180;
            context.rotate(deg);
            context.fillText(txt, 0, 0);
            context.rotate(-deg);
            context.translate(-x, -y);
            arr[i] = txt
        }
        num = arr.join('');

        // 绘制干扰线条
        for (var i = 0; i < 8; i++) {
            context.beginPath();
            context.moveTo(Math.random() * 120, Math.random() * 40);
            context.lineTo(Math.random() * 120, Math.random() * 40);
            context.strokeStyle = getColor();
            context.stroke();
        }

        // 绘制干扰点
        for (var i = 0; i < 20; i++) {
            context.beginPath();
            var x = Math.random() * 120;
            var y = Math.random() * 40;
            context.moveTo(x, y);
            context.lineTo(x + 1, y + 1);
            context.strokeStyle = getColor();
            context.stroke();
        }
    }

    // 验证用户输入
    function validate() {
        button.onclick = function (event) {
            const text = input.value;
            if (text === num) {
                validationMessage.textContent = "";
                //alert('验证码正确');
            } else {
                event.preventDefault(); // 如果验证未通过，则阻止表单的默认提交事件
                validationMessage.textContent = "验证码错误";
                //alert('验证码错误');
                draw();
            }
        }
    }


    // 初始化函数
    function init() {
        draw();
        canvas.onclick = draw;
        validate();
    }

    return {
        init: init
    };

})();

